
#include "enbt.h"
#include "process_cmd.h"
#include "command.h"
#include "imp_commands.h"
#include "tokenize.h"
#include <stdio.h>
#include <stdlib.h>


int process_cmd(struct enbt_state *state, char *cmdline)
{
	int i, j;
	int errorlevel = 0;
	int cmd_len[20]; //can have max of 20 commands in 1 line
	int cmd_count = 0;
	int cmd_start = 0;

	int argc = 0;
	char **argv;

	tokenize(cmdline, &argc, &argv);
	
	//for(i=0; i<argc; i++)
	//	printf("argv[%i]= %s\n", i, argv[i]);
		
	
	for (i=0; i<argc; i++)
	{
		if (strcmp(argv[i], ";") == 0)
		{
			printf("cmd len: %i\n", i-cmd_start);
			cmd_len[cmd_count] = i - cmd_start;
			cmd_count++;
			cmd_start = i+1;
			if (cmd_count >= sizeof(cmd_len))
			{
				printf("Error: Too many commands on one line\n");
				errorlevel = 3;
			}
		}
	}
	
	if (i - cmd_start > 0)
	{
		cmd_len[cmd_count] = i - cmd_start;
		cmd_count++;
	}

	if (errorlevel == 0)
	{
		cmd_start = 0;
		for(j=0; j<cmd_count; j++)
		{
			for(i=0; i<imp_commands_size; i++)
			{
				if (strcmp(imp_commands[i].name, argv[cmd_start]) == 0)
				{
					errorlevel = imp_commands[i].function(state, cmd_len[j], &argv[cmd_start]);
					i = -1;
					break;
				}
			}
			if (i == imp_commands_size)
			{
				printf("Error: command not found\n");
				errorlevel = 2;
				break;
			}
			cmd_start += cmd_len[j]+1;
		}
	}
	
	for(i=0; i<argc; i++)
		free(argv[i]);
	free(argv);

	return errorlevel;
}

